import { ERROR_CODE, MQTT_TOPIC } from '../../constant.js'
import logger from '../utils/logger.js'
import { userDao } from '../db/dao/user.js'
import { User } from '../db/pojo/user.js'
import { v4 } from 'uuid'
import { md5 } from '../utils/encrypt.js'

async function handleUserRegister(mqttClient, data) {
    logger.info(`[MQTT] handle register user: ${JSON.stringify(data)} success!`)
    
    const { account, password, email, age } = data
    const response = {
        error: ERROR_CODE.SUCCESS,
        message: ''
    }
    if (!account || !password) {
        response.error = ERROR_CODE.CLIENT_ERROR
        response.message = 'account or password required!'
    }

    const accountExisted = userDao.queryWithConditions([`account = '${account}'`])
    if (accountExisted.length > 0) {
        response.error = ERROR_CODE.USER_EXISTS
        response.message = 'user existed!'
    }
    
    if (response.error === ERROR_CODE.SUCCESS) {
        const user = new User({
            id: v4(),
            account,
            password: md5(password),
            email,
            age
        })
        const id = userDao.insert(user)
        response.data = { id }
        response.message = `account: ${account} register success!`
    }

    await mqttClient.publishAsync(MQTT_TOPIC.USER_REGISTER_RESULT, JSON.stringify(response))
}

const map = {
    [MQTT_TOPIC.USER_REGISTER]: handleUserRegister
}

export function findHandler(topic) {
    return map[topic]
}
